package com.meet.dao;

import com.meet.entity.User;
import com.meet.util.JDBCutil;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao{
    private PreparedStatement preparedStatement;
    private ResultSet resultSet;
    /*@Override
    public User login(String userName, String password) throws SQLException {

        Connection con= DButil.getConnection();
        preparedStatement=con.prepareStatement("select * from user  where user_name=? and password=?");
        preparedStatement.setObject(1,userName);
        preparedStatement.setObject(2,password);
        resultSet=preparedStatement.executeQuery();

        User user=null;
        if (resultSet.next()) {
            user=new User(resultSet.getInt(1), resultSet.getString(2), resultSet.getString(3));
        }
        DButil.closeConnection();
        return user;
    }*/

    @Override
    public List<String> getUrl(Integer id) throws SQLException {
        Connection connection = null;
        connection = JDBCutil.getConnection();
        preparedStatement=connection.prepareStatement("select c.url from record c, record_role d where  c.id=d.record_id and d.r_id in (select b.r_id  from workers a, user_role b where a.id=b.u_id and a.id=?)");
        preparedStatement.setObject(1,id);
        resultSet=preparedStatement.executeQuery();
        List<String> list=new ArrayList<String>();
        while(resultSet.next()){
           String url= resultSet.getString(1);
            //System.out.println(url);
            list.add(url);
        }
        resultSet.close();
        JDBCutil.closeConnection();
        return list;
    }


    //侯喆做得登录
//    private PreparedStatement preparedStatement;
//    private ResultSet resultSet;

    /**
     * 获取数据
     *
     * @param name
     * @param password
     * @return
     * @throws SQLException
     */
    @Override
    public User getUser(String name, String password) throws SQLException {

        User user = new User();

        //连接数据库
        Connection connection = JDBCutil.getConnection();

        String sql = "select id from workers where u_name = ? and u_password = ?";

        preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setObject(1,name);
        preparedStatement.setObject(2,password);

        resultSet = preparedStatement.executeQuery();
        if (!resultSet.next()){
            throw new SQLException("用户名或密码错误");
        }

        user.setId(resultSet.getInt(1));
        user.setName(name);
        user.setPassword(password);

        JDBCutil.closeConnection();
        return user;
    }
}
